<?php
class download {
    
    public static function downloadp($provider, $search, $keywords, $direct = true, $check_only = false, $bad_keywords)
    {
        $output = "";

        if($provider == "tpb")
            $output = download::tpb($search, $keywords, $direct, $check_only, $bad_keywords);
        else if($provider == "isohunt")
            $output = download::isohunt($search, $keywords, $direct, $check_only, $bad_keywords);
        else if($provider == "filesTube")
            $output = download::filesTube($search, $keywords, $direct, $check_only, $bad_keywords);
        else if($provider == "ahashare")
            $output = download::ahashare($search, $keywords, $direct, $check_only, $bad_keywords);
        else if($provider == "kat")
            $output = download::kat($search, $keywords, $direct, $check_only, $bad_keywords);
        else if($provider == "subscene")
            $output = download::subscene($search, $keywords, $direct, $check_only, $bad_keywords);
        else if($provider == "others")
            $output = download::others($search, $keywords, $direct, $check_only, $bad_keywords);

        else if($provider == "isohunt2")
            $output = download::isohunt2($search, $keywords, $direct, $check_only, $bad_keywords);

        if($check_only)
            return $output;
        else
            echo $output;
    }

    public static function others($search, $keywords, $direct, $check_only, $bad_keywords)
    {
        $keywords_array = explode('-', $keywords);
        $keywords_hash = array();

        foreach($keywords_array as $keyword)
        {
            $link['title'] = str_replace("+", " ", $search).' '.$keyword;
            $link['href'] = "#";
            $link['size'] = "1 GB";
            $link['seeds'] = "2";
            $link['peers'] = "0";
            $link['favicon'] = "";

            $keywords_hash[$keyword] = array();

            array_push($keywords_hash[$keyword], $link);
        }

        return $_GET['jsonp_callback'] . '(' . json_encode($keywords_hash) . ');';

    }

    public static function kat($search, $keywords, $direct, $check_only, $bad_keywords)
    {
        $url = "http://kat.ph/usearch/$search/?field=seeders&sorder=desc";
        $rows_xpath = '//table[@class="data"]//tr';
        $link_xpath = '//td[1]/div[@class="torrentname"]//a[2]';
        $direct_link_xpath = '//a[@title="Torrent magnet link"]';
        $size_xpath = '//td[2]';
        $seeds_xpath = '//td[5]';
        $peers_xpath = '//td[6]';


        return download::get_links($direct, $search, $url, $rows_xpath, $link_xpath, $direct_link_xpath, $keywords, $size_xpath, $seeds_xpath, $peers_xpath, true,null,null,null,$check_only, $bad_keywords);
    }
    public static function subscene($search, $keywords, $direct, $check_only, $bad_keywords, $langcode=2)
    {
        //english = 13

        $encoded_url = "http://suuble.com/login.aspx?ReturnUrl=&q=$search&l=";
        $c = curl_init($encoded_url);
        curl_setopt ($c, CURLOPT_COOKIE, 'languageIds='.$langcode.'-');
        curl_setopt ($c, CURLOPT_RETURNTRANSFER, true);
        $page = curl_exec ($c);
        curl_close ($c);
        /////////////////

        $url = $encoded_url;
        $rows_xpath = '//ul[@class="subtitles"]//li[not(@class)]';
        $link_xpath = '//a';
        $direct_link_xpath = null;
        $size_xpath = '//span';
        $seeds_xpath = null;
        $peers_xpath = null;

        return download::get_links($direct, $search, $url, $rows_xpath, $link_xpath, $direct_link_xpath, $keywords, $size_xpath, $seeds_xpath, $peers_xpath, false, "http://subscene.com/favicon.ico", $page, 'Arabic',$check_only, $bad_keywords);
    }
    public static function isohunt($search, $keywords, $direct, $check_only, $bad_keywords)
    {
        $url = "http://isohunt.com/torrents/$search?iht=-1&ihp=1&ihs1=1&iho1=d";
        $rows_xpath = '//table[@id="serps"]/tr[@class="hlRow"]';
        $link_xpath = '//td[3]//a[2]';
        $direct_link_xpath = null;
        $size_xpath = '//td[4]';
        $seeds_xpath = '//td[5]';
        $peers_xpath = '//td[6]';
        return download::get_links($direct, $search, $url, $rows_xpath, $link_xpath, $direct_link_xpath, $keywords, $size_xpath, $seeds_xpath, $peers_xpath,false,null,null,null,$check_only, $bad_keywords);
    }
    public static function isohunt2($search, $keywords, $direct, $check_only, $bad_keywords)
    {
        $url = "http://isohunt.com/torrents/$search?iht=-1&ihp=1&ihs1=1&iho1=d";
        $rows_xpath = '//table[@id="serps"]/tr[@class="hlRow"]';
        $link_xpath = '//td[3]//a[2]';
        $direct_link_xpath = null;
        $size_xpath = '//td[4]';
        $seeds_xpath = '//td[5]';
        $peers_xpath = '//td[6]';
        return download::get_links($direct, $search, $url, $rows_xpath, $link_xpath, $direct_link_xpath, $keywords, $size_xpath, $seeds_xpath, $peers_xpath,false,null,null,null,$check_only, $bad_keywords, true);
    }

    public static function tpb($search, $keywords, $direct, $check_only, $bad_keywords)
    {
        $url = "http://thepiratebay.se/search/$search/0/7/0";
        $rows_xpath = '//table[@id="searchResult"]//tr';
        $link_xpath = '//td[2]//a';
        $direct_link_xpath = '//td[2]/a[1]';
        $size_xpath = '//font@@/[0-9]*\.?[0-9]*...iB/';
        $seeds_xpath = '//td[3]';
        $peers_xpath = '//td[4]';
        return download::get_links($direct, $search, $url, $rows_xpath, $link_xpath, $direct_link_xpath, $keywords, $size_xpath, $seeds_xpath, $peers_xpath, false,null,null,null,$check_only, $bad_keywords);
    }
    public static function ahashare($search, $keywords, $direct, $check_only, $bad_keywords)
    {
        $url = "http://www.ahashare.com/torrents-search.php?search=$search&sort=seeders&order=desc";
        $rows_xpath = '//table[@class="ttable_headinner"]//tr';
        $link_xpath = '//td[2]//a';
        $direct_link_xpath = '//td[3]//a';
        $size_xpath = '//td[5]';
        $seeds_xpath = '//td[6]';
        $peers_xpath = '//td[7]';
        return download::get_links($direct, $search, $url, $rows_xpath, $link_xpath, $direct_link_xpath, $keywords, $size_xpath, $seeds_xpath, $peers_xpath, false, "http://ahashare.com/images/favicon.ico", null,null,$check_only, $bad_keywords);
    }

    public static function filesTube($search, $keywords, $direct, $check_only, $bad_keywords)
    {
        $url = "http://www.filestube.com/query.html?q=$search&select=All";
        $rows_xpath = '//div[@id="newresult"]';
        $link_xpath = '//a';
        $direct_link_xpath = null;
        $size_xpath = '//span@@/[0-9]*\.?[0-9]* .B/';
        $seeds_xpath = null;
        $peers_xpath = null;
        return download::get_links($direct, $search, $url, $rows_xpath, $link_xpath, $direct_link_xpath, $keywords, $size_xpath, $seeds_xpath, $peers_xpath, false, "http://static.filestube.com/files/images/favicon.ico",null,null,$check_only, $bad_keywords);
    }

    public static function get_links($direct, $search, $url, $rows_xpath, $link_xpath, $direct_link_xpath, $keywords, $size_xpath = null, $seeds_xpath = null, $peers_xpath = null, $uncomprise = false, $favicon = null, $content = null, $fixed_tab=null, $check_only=false, $bad_keywords=null, $print=false)
    {
        if($keywords == "undefined" || !$keywords)
            $keywords = "others";
        else
            $keywords .="-others";


        if($fixed_tab)
            $keywords .="-$fixed_tab";

        $keywords .="-nomatch";

        $keywords_array = explode('-', $keywords);
        $keywords_hash = array();



        foreach($keywords_array as $keyword)
        {
            $keywords_hash[$keyword] = array();
        }

        $domain = util::get_domain($url);
        if($favicon == null)
            $favicon = "http://".$domain.'/favicon.ico';

        if($content == null)
            $content = util::read_url($url);

        if($print)
            echo "11111111111".$content."2222222222";

        if($uncomprise)
            $content = download::gunzip($content);

        $domxpath = download::get_domxpath($content);

        $rows = $domxpath->query($rows_xpath);


        foreach($rows as $row)
        {
            //echo download::convert_Node_to_html($row);
            $row_html =  download::convert_Node_to_html($row);
            $domxpath = download::get_domxpath($row_html);
            $hrefs = $domxpath->query($link_xpath);
            if($size_xpath)
            {
                $sizes_segs = explode('@@', $size_xpath);
                $sizes = $domxpath->query($sizes_segs[0]);
            }
            if($seeds_xpath)
                $seeds = $domxpath->query($seeds_xpath);
            if($peers_xpath)
                $peers = $domxpath->query($peers_xpath);

            if($direct && $direct_link_xpath)
                $direct_links = $domxpath->query($direct_link_xpath);

            if($hrefs->length > 0)
            {
                $title = trim(str_replace(array("\r\n", "\r", "\t"), "\n", $hrefs->item(0)->nodeValue));
                $keyword = download::which_keyword($title, $keywords_array);
                if($keyword)
                {
                    $link['href'] = util::add_domain_to_link($domain, $hrefs->item(0)->getAttribute('href'));
                    $link['title'] = $title;

                    if($direct && $direct_link_xpath)
                    {
                        $link['href'] = $direct_links->item(0)->getAttribute('href');
                        if(strpos($link['href'], 'magnet') !== 0 )
                        {
                            include('include/config.php');
                            $link['href'] = util::add_domain_to_link($domain, $link['href']);
                            $link['href'] = $server_url.$folder_url.'dl/'.base64_encode($link['href'].'&.torrent');
                        }
                    }
                    if($domain == 'isohunt.com')
                    {
                        if($direct)
                        {
                            //http://isohunt.com/torrent_details/106315229/ice+age?tab=summary
                            //http://ca.isohunt.com/download/106315229/ice+age.torrent
                            $link['href'] = str_replace('isohunt.com/torrent_details', 'ca.isohunt.com/download', $link['href']);
                            $link['href'] = str_replace('?tab=summary', '.torrent', $link['href']);

                            include('include/config.php');
                            $link['href'] = util::add_domain_to_link($domain, $link['href']);
                            $link['href'] = $server_url.$folder_url.'dl/'.base64_encode($link['href']);
                        }
                    }

                    if($sizes)
                    {
                        $link['size'] = $sizes->item(0)->nodeValue;
                        if($sizes_segs[1]) //if has regex
                        {
                            $link['size'] = download::evaluate_regex($link['size'], $sizes_segs[1]);
                        }
                    }
                    else
                        $link['size'] = "-";
                    if($seeds)
                        $link['seeds'] = $seeds->item(0)->nodeValue;
                    else
                        $link['seeds'] = "-";
                    if($peers)
                        $link['peers'] = $peers->item(0)->nodeValue;
                    else
                        $link['peers'] = "-";

                    $link['favicon'] = $favicon;


                    if($fixed_tab)
                    {
                        if(download::validate_link($link['title'], $search, $bad_keywords))
                            array_push($keywords_hash[$fixed_tab], $link);
                        else
                            array_push($keywords_hash['nomatch'], $link);
                    }

                    else
                    {
                        if(download::validate_link($link['title'], $search, $bad_keywords))
                        {
                            array_push($keywords_hash[$keyword], $link);
                        }
                        else
                            array_push($keywords_hash['nomatch'], $link);
                    }

                }
            }
        }



        $clean_keywords_hash = array();
        foreach($keywords_hash as $key => $k)
        {
            if(count($k) > 0)
                $clean_keywords_hash[$key] = $k;
        }
        //if check mode
        if($check_only)
        {
            return $clean_keywords_hash;
        }
        return $_GET['jsonp_callback'] . '(' . json_encode($clean_keywords_hash) . ');';
    }

    public static function validate_link($link_title, $search, $bad_keywords=null)
    {
        //return true;
        $search_array = explode( '+', $search );

        foreach ($search_array as $word)
        {
            if($word && strpos(strtolower($link_title), strtolower($word)) === false)
            {
                return false;
            }
        }
        
        //invalid stuff
        if($bad_keywords)
        {
            $pcs = explode('-',$bad_keywords);
            foreach($pcs as $bk)
            {
                if(preg_match("/\\W$bk\\W/i", $link_title)) //any bad keyword will render this as bad result
                    return false;
            }
        }
        //regex
        
        return true;
    }

    public static function evaluate_regex($text, $regex)
    {
        preg_match($regex, $text, $matches);
        return $matches[0];
    }

    public static function which_keyword($title, $keywords_array)
    {
        foreach ($keywords_array as $keyword)
        {
            if($keyword)
                if(strpos(strtolower($title), strtolower($keyword)) !== false)
                {
                    return $keyword;
                }
        }
        return "others";
    }

    public static function convert_DOMNodeList_to_html($domNodeList)
    {
        $temp_dom = new DOMDocument();
        foreach($domNodeList as $n)
        {
            $temp_dom->appendChild($temp_dom->importNode($n,true));
        }
        return $temp_dom->saveHTML();
    }
    public static function convert_Node_to_html($node)
    {
        $temp_dom = new DOMDocument();
        $temp_dom->appendChild($temp_dom->importNode($node,true));
        return $temp_dom->saveHTML();
    }
    public static function get_domxpath($content)
    {
        $html = new DOMDocument();
        @$html->loadHTML($content);
        $domxpath = new DOMXPath( $html );
        return $domxpath;
    }

    //decodes a gzip response
    public static function gunzip($zipped) {
        $offset = 0;
        if (substr($zipped,0,2) == "\x1f\x8b")
            $offset = 2;
        if (substr($zipped,$offset,1) == "\x08")  {
            # file_put_contents("tmp.gz", substr($zipped, $offset - 2));
            return gzinflate(substr($zipped, $offset + 8));
        }
        return "Unknown Format";
    }
}

?>